package com.playball.lottery.frm.hemai;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.PullDownView;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.customview.PullDownView.OnPullDownListener;
import com.playball.lottery.eventmanger.EventManager;
import com.playball.lottery.eventmanger.EventType;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.FrmWorkStatus;


/**
 * 合买大厅
 * 
 * @author Administrator
 * 
 */
public class HeMaiMainActivity extends BaseActivity implements OnPullDownListener, OnItemClickListener {

	/** 顶部菜单栏 */
	private TextView top_title_back;
	private TextView top_title_right_btn;
	/** 进度排序相关 */
	private View hemai_main_ll_progress;
	private TextView hemai_main_tv_progress;
	private TextView hemai_main_tv_progress_order_0;
	private TextView hemai_main_tv_progress_order_1;
	/** 战绩排序相关 */
	private View hemai_main_ll_grade;
	private TextView hemai_main_tv_grade;
	private TextView hemai_main_tv_grade_order_0;
	private TextView hemai_main_tv_grade_order_1;
	/** 总额排序相关 */
	private View hemai_main_ll_total;
	private TextView hemai_main_tv_total;
	private TextView hemai_main_tv_total_order_0;
	private TextView hemai_main_tv_total_order_1;
	/** 刷新按钮 */
	private ImageButton hemai_main_ib_refresh;
	/** 列表 */
	private PullDownView hemai_lv_process;

	private ListView listView;

	/** 排序彩种 */
	private int LottID = 0;
	/** 用于排序的列名（3=进度， 1=总额 ，5=战绩） */
	private int OrderField = 0;
	/** 排序方式（0：倒序；1：正序） */
	private int OrderType = 0;
	/** 第几页 */
	private int PageNo = 1;
	/** 每页条数 */
	private int PageSize = 10;

	/** 记录总条数 */
	private int intTotalNum;
	/** 网络获取的数据 */
	private List<Map<String, Object>> netDataList;
	/** 是否有下一页 */
	private boolean nextPage = false;
	/** 是否按更多 */
	private boolean isPressMore = false;
	/** 填充到listview的本地数据 */
	private List<Map<String, Object>> mDataList;
	/** 合买大厅适配器 */
	private HemaiMainProcessListAdapter hemaiAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.hemai_main2);
		initView();
	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	/**
	 * 初始化组件
	 */
	private void initView() {
		top_title_back = (TextView) findViewById(R.id.top_title_back);
		top_title_right_btn = (TextView) findViewById(R.id.top_title_right_btn);

		hemai_main_ll_progress = findViewById(R.id.hemai_main_ll_progress);
		hemai_main_tv_progress = (TextView) findViewById(R.id.hemai_main_tv_progress);
		hemai_main_tv_progress_order_0 = (TextView) findViewById(R.id.hemai_main_tv_progress_order_0);
		hemai_main_tv_progress_order_1 = (TextView) findViewById(R.id.hemai_main_tv_progress_order_1);

		hemai_main_ll_grade = findViewById(R.id.hemai_main_ll_grade);
		hemai_main_tv_grade = (TextView) findViewById(R.id.hemai_main_tv_grade);
		hemai_main_tv_grade_order_0 = (TextView) findViewById(R.id.hemai_main_tv_grade_order_0);
		hemai_main_tv_grade_order_1 = (TextView) findViewById(R.id.hemai_main_tv_grade_order_1);

		hemai_main_ll_total = findViewById(R.id.hemai_main_ll_total);
		hemai_main_tv_total = (TextView) findViewById(R.id.hemai_main_tv_total);
		hemai_main_tv_total_order_0 = (TextView) findViewById(R.id.hemai_main_tv_total_order_0);
		hemai_main_tv_total_order_1 = (TextView) findViewById(R.id.hemai_main_tv_total_order_1);

		hemai_main_ib_refresh = (ImageButton) findViewById(R.id.hemai_main_ib_refresh);

		// hemai_lv_process = (PullDownView)
		// findViewById(R.id.hemai_lv_process);
		hemai_lv_process.setOnPullDownListener(this);

		listView = hemai_lv_process.getListView();
		listView.setOnItemClickListener(this);

		top_title_back.setOnClickListener(btn_onclick);
		top_title_right_btn.setOnClickListener(btn_onclick);
		hemai_main_ll_progress.setOnClickListener(btn_onclick);
		hemai_main_ll_grade.setOnClickListener(btn_onclick);
		hemai_main_ll_total.setOnClickListener(btn_onclick);
		hemai_main_ib_refresh.setOnClickListener(btn_onclick);

		sort_click(3);
	}

	/**
	 * 
	 * @param orderField2
	 *            排序列名
	 */
	private void sort_click(int orderField2) {
		switch (orderField2) {
		case 3: // 进度
			if (orderField2 == OrderField) {
				OrderType = (hemai_main_tv_progress_order_0.getVisibility() == View.GONE ? 0 : 1);
			} else {
				OrderField = orderField2;
				OrderType = (hemai_main_tv_progress_order_0.getVisibility() == View.GONE ? 1 : 0);
			}
			hemai_main_ll_progress.setSelected(true);
			hemai_main_tv_progress.setSelected(true);
			hemai_main_tv_progress_order_0.setVisibility(View.GONE);
			hemai_main_tv_progress_order_1.setVisibility(View.GONE);
			if (OrderType == 0) {
				hemai_main_tv_progress_order_0.setVisibility(View.VISIBLE);
				hemai_main_tv_progress_order_0.setSelected(true);
			} else {
				hemai_main_tv_progress_order_1.setVisibility(View.VISIBLE);
				hemai_main_tv_progress_order_1.setSelected(true);
			}
			hemai_main_ll_grade.setSelected(false);
			hemai_main_tv_grade.setSelected(false);
			hemai_main_tv_grade_order_0.setSelected(false);
			hemai_main_tv_grade_order_1.setSelected(false);
			hemai_main_ll_total.setSelected(false);
			hemai_main_tv_total.setSelected(false);
			hemai_main_tv_total_order_0.setSelected(false);
			hemai_main_tv_total_order_1.setSelected(false);
			break;
		case 5: // 战绩
			if (orderField2 == OrderField) {
				OrderType = (hemai_main_tv_grade_order_0.getVisibility() == View.GONE ? 0 : 1);
			} else {
				OrderField = orderField2;
				OrderType = (hemai_main_tv_grade_order_0.getVisibility() == View.GONE ? 1 : 0);
			}
			hemai_main_ll_progress.setSelected(false);
			hemai_main_tv_progress.setSelected(false);
			hemai_main_tv_progress_order_0.setSelected(false);
			hemai_main_tv_progress_order_1.setSelected(false);
			hemai_main_ll_grade.setSelected(true);
			hemai_main_tv_grade.setSelected(true);
			hemai_main_tv_grade_order_0.setVisibility(View.GONE);
			hemai_main_tv_grade_order_1.setVisibility(View.GONE);
			if (OrderType == 0) {
				hemai_main_tv_grade_order_0.setVisibility(View.VISIBLE);
				hemai_main_tv_grade_order_0.setSelected(true);
			} else {
				hemai_main_tv_grade_order_1.setVisibility(View.VISIBLE);
				hemai_main_tv_grade_order_1.setSelected(true);
			}
			hemai_main_ll_total.setSelected(false);
			hemai_main_tv_total.setSelected(false);
			hemai_main_tv_total_order_0.setSelected(false);
			hemai_main_tv_total_order_1.setSelected(false);
			break;
		case 1: // 总额
			if (orderField2 == OrderField) {
				OrderType = (hemai_main_tv_total_order_0.getVisibility() == View.GONE ? 0 : 1);
			} else {
				OrderField = orderField2;
				OrderType = (hemai_main_tv_total_order_0.getVisibility() == View.GONE ? 1 : 0);
			}
			hemai_main_ll_progress.setSelected(false);
			hemai_main_tv_progress.setSelected(false);
			hemai_main_tv_progress_order_0.setSelected(false);
			hemai_main_tv_progress_order_1.setSelected(false);
			hemai_main_ll_grade.setSelected(false);
			hemai_main_tv_grade.setSelected(false);
			hemai_main_tv_grade_order_0.setSelected(false);
			hemai_main_tv_grade_order_1.setSelected(false);
			hemai_main_ll_total.setSelected(true);
			hemai_main_tv_total.setSelected(true);
			hemai_main_tv_total_order_0.setVisibility(View.GONE);
			hemai_main_tv_total_order_1.setVisibility(View.GONE);
			if (OrderType == 0) {
				hemai_main_tv_total_order_0.setVisibility(View.VISIBLE);
				hemai_main_tv_total_order_0.setSelected(true);
			} else {
				hemai_main_tv_total_order_1.setVisibility(View.VISIBLE);
				hemai_main_tv_total_order_1.setSelected(true);
			}
			break;
		}
		PageNo = 1;
		startHBuyThread();
	}

	/**
	 * 从服务器获取合买列表网络数据
	 * 
	 * @param strLotId彩种
	 *            所有=0，双色球=5,超级大乐透=39，其他数字彩=-1. etc.
	 * @param orderType
	 *            排序方式（0：倒序；1：正序）
	 * @param orderField
	 *            3=进度， 1=总额 ，5=战绩
	 * @param pageNo
	 *            第几页
	 */
	private void startHBuyThread() {

		AsyncLoader task = new AsyncLoader();
		String[] dyn = new String[2];
		JSONObject params = new JSONObject();

		try {
			// 设置请求所需参数
			params.put("LottID", LottID);
			params.put("OrderField", OrderField);
			params.put("OrderType", OrderType);
			params.put("PageNo", PageNo);
			params.put("PageSize", 10);
		} catch (JSONException ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		dyn[0] = params.toString();
		dyn[1] = "206";// 212//合买中心方案列表
		// Log.e("startHBuyThread= ", dyn[1].toString() + " " +
		// dyn[0].toString());
		task.execute(dyn);
	}

	/**
	 * 接受处理网络数据
	 * 
	 * @author Administrator
	 * 
	 */
	class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		String action;
		ShowTipDialog showdialog = new ShowTipDialog();

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(HeMaiMainActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... paramsArr) {
			// 处理后台执行的任务，在后台线程执行
			String strResult = null;

			action = paramsArr[1];
			// 获取请求返回值
			strResult = GetRequestParams.getRequestResult(paramsArr[0], action, getApplicationContext());
			// 获取请求返回值
			return strResult;
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				// 合买方案列表
				if (action.equals("206")) {
					HBuy(result);
				}
				showdialog.closeDialog();
			} else {
				Toast.makeText(HeMaiMainActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}

	}

	/**
	 * 处理网络返回数据及显示listview视图
	 * 
	 * @param strResult
	 */
	public void HBuy(String strResult) {
		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			// 接下来的就是JSON对象的操作了
			if (Integer.parseInt(js.getString("Code")) == 0) {
				JSONTokener jsonParser1 = new JSONTokener(strResult);
				JSONObject js1 = (JSONObject) jsonParser1.nextValue();
				if (js1.getString("Data") != null && !"".equals(js1.getString("Data"))) {
					intTotalNum = Integer.parseInt(String.valueOf(ConvertJsonToList.getMap(js1.getString("Data")).get(
							"Count")));
					// Log.d("hemaimain", "intTotalNum= "+intTotalNum);////
					// 记录总条数
					List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
					list = ConvertJsonToList.getList(String.valueOf(ConvertJsonToList.getMap(js1.getString("Data"))
							.get("item")));
					netDataList = new ArrayList<Map<String, Object>>(list);
				} else {
					intTotalNum = 0;
					if (netDataList != null) {
						netDataList.clear();
					}
				}
				showHList();
			} else {
				Toast.makeText(HeMaiMainActivity.this, js.getString("Data"), Toast.LENGTH_SHORT).show();
			}
		} catch (JSONException e) {
			// 异常处理代码
			Log.e("error", e.toString());
		}
	}

	/**
	 * 放入数据，显示listview视图
	 */
	public void showHList() {
		int maxPage = (intTotalNum % PageSize == 0) ? (intTotalNum / PageSize) : (intTotalNum / PageSize + 1);
		// Log.e("maxPage", maxPage + "");
		if (PageNo < maxPage) {
			nextPage = true;
		} else {
			nextPage = false;
		}
		// Log.e("nextPage= ", nextPage + "");
		// //获取更多数据之外的请求，如首次请求数据，刷新，点击进度，战绩，总额
		if (!isPressMore) {
			// mDataList = HemaiDateUtil.SortListData(netDataList, intOrderType,
			// intOrderField);
			mDataList = netDataList;
			// Log.e("==isPressMore== ", isPressMore + "");
			// Log.e("==netDataList== ", netDataList.toString());
			// Log.e("==mDataList== ", mDataList.toString());
			// 填充UI,listview
			if (mDataList != null) {
				hemaiAdapter = new HemaiMainProcessListAdapter(HeMaiMainActivity.this, mDataList);
				listView.setAdapter(hemaiAdapter);
			}
			// 隐藏并且禁用头部刷新
			hemai_lv_process.setHideHeader();
			// 显示并且可以使用头部刷新
			// mPullDownView.setShowHeader();

			/** 关闭 刷新完毕 ***/
			// mPullDownView.RefreshComplete();// 这个事线程安全的 可看源代码

		} else {
			// 获取更多数据
			// mDataList.addAll(HemaiDateUtil.SortListData(netDataList,
			// intOrderType, intOrderField));
			mDataList.addAll(netDataList);
			hemaiAdapter.setData(mDataList);
			hemaiAdapter.notifyDataSetChanged();

			// Log.e("==netDataList2== ", netDataList.toString());
			// Log.e("==mDataList2== ", mDataList.toString());
			// Log.e("==isPressMore2== ", isPressMore + "");

		}
		if (mDataList == null) {
			Toast.makeText(HeMaiMainActivity.this, R.string.temporarily_no_data, Toast.LENGTH_LONG).show();
		}
		// 判断是否有下一页
		if (nextPage) {
			// 显示并启用自动获取更多
			hemai_lv_process.setShowFooter();
			// 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
			hemai_lv_process.enableAutoFetchMore(true, 1);
		} else {
			// 隐藏 并禁用尾部
			hemai_lv_process.setHideFooter();
			// 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
			hemai_lv_process.enableAutoFetchMore(false, 1);
		}
		// 告诉它获取更多完毕 这个事线程安全的 可看源代码
		hemai_lv_process.notifyDidMore();
		isPressMore = false;
	}

	/**
	 * 按钮点击事件
	 */
	private View.OnClickListener btn_onclick = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.top_title_back:
				EventManager.getInstance().onEvent(EventType.EV_UI_FRM_MAIN_JUMP, FrmWorkStatus.MAINHOME);
				break;
			case R.id.top_title_right_btn:
				EventManager.getInstance().onEvent(EventType.EV_UI_BLL_SCROLL_TO_RIGHT, null);
				break;
			case R.id.hemai_main_ll_progress:
				sort_click(3);
				break;
			case R.id.hemai_main_ll_grade:
				sort_click(5);
				break;
			case R.id.hemai_main_ll_total:
				sort_click(1);
				break;
			case R.id.hemai_main_ib_refresh:
				onRefresh();
				break;
			}
		}
	};

	// /**
	// * 点击事件（XML）
	// * @param v
	// */
	// public void btn_onclick(View v) {
	// switch(v.getId()) {
	// case R.id.top_title_back:
	// break;
	// case R.id.top_title_right_btn:
	// break;
	// case R.id.hemai_main_ll_progress:
	// sort_click(3);
	// break;
	// case R.id.hemai_main_ll_grade:
	// sort_click(5);
	// break;
	// case R.id.hemai_main_ll_total:
	// sort_click(1);
	// break;
	// case R.id.hemai_main_ib_refresh:
	// onRefresh();
	// break;
	// }
	// }

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		// 发送刷新请求
		PageNo = 1;
		startHBuyThread();
	}

	@Override
	public void onMore() {
		// TODO Auto-generated method stub
		isPressMore = true;
		// 发送更多请求
		PageNo++;
		startHBuyThread();
	}

}
